//
//  AppDelegate.m
//  Gunterapple
//
//  Created by 热带雨林 on 2020/3/16.
//  Copyright © 2020 热带雨林. All rights reserved.
//

#import "AppDelegate.h"
#import "ViewController.h"
#import "AdvertiseView.h"
#import "AdVertiseViewController.h"
#import <Photos/Photos.h>
@interface AppDelegate ()



@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    //首先判断系统是否支持3D touch
    if(self.window.traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable){
        //shortcutItems数组
        NSMutableArray *arrayShortcutItems = (NSMutableArray *)[UIApplication sharedApplication].shortcutItems;
        
        //单个shortcutItem
        UIApplicationShortcutItem *item1 = [[UIApplicationShortcutItem alloc]initWithType:@"message" localizedTitle:@"新消息" localizedSubtitle:nil icon:[UIApplicationShortcutIcon iconWithType:UIApplicationShortcutIconTypeCompose] userInfo:nil];
        
        UIApplicationShortcutItem *item2 = [[UIApplicationShortcutItem alloc]initWithType:@"search" localizedTitle:@"搜索" localizedSubtitle:nil icon:[UIApplicationShortcutIcon iconWithType:UIApplicationShortcutIconTypeSearch] userInfo:nil];
        
        UIApplicationShortcutItem *item3 = [[UIApplicationShortcutItem alloc]initWithType:@"collect" localizedTitle:@"收藏" localizedSubtitle:nil icon:[UIApplicationShortcutIcon iconWithType:UIApplicationShortcutIconTypeLove] userInfo:nil];
        
        UIApplicationShortcutItem *item4 = [[UIApplicationShortcutItem alloc]initWithType:@"share" localizedTitle:@"分享" localizedSubtitle:nil icon:[UIApplicationShortcutIcon iconWithType:UIApplicationShortcutIconTypeShare] userInfo:nil];
        
        [arrayShortcutItems addObject:item1];
        [arrayShortcutItems addObject:item2];
        [arrayShortcutItems addObject:item3];
        [arrayShortcutItems addObject:item4];
    }
    
//    [[NSNotificationCenter defaultCenter] addObserver:self
//                                                selector:@selector(userDidTakeScreenshotNotification:)
//                                                    name:UIApplicationUserDidTakeScreenshotNotification object:nil];
    
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(takeScreenSheetAction:) name:UIApplicationUserDidTakeScreenshotNotification object:nil];
    
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(saveImageToPhotoAlbum:) name:UIApplicationUserDidTakeScreenshotNotification object:nil];
    //同时兼容iOS13与iOS12
    if(@available(iOS 13,*)){
        return YES;
    }else{
        self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
        self.window = [[UIApplication sharedApplication] delegate].window;
//        self.window.rootViewController = [[UINavigationController alloc]initWithRootViewController:[[ViewController alloc]init]];
        self.window.rootViewController = [[AdVertiseViewController alloc]init];
        [self.window makeKeyAndVisible];
        return YES;
    }
    
}

-(void)takeScreenSheetAction:(NSNotification *)notification{

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

        PHFetchOptions *options = [[PHFetchOptions alloc] init];

        options.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:NO]];

        PHFetchResult *assetsFetchResults = [PHAsset fetchAssetsWithOptions:options];

        PHAsset *asset = [assetsFetchResults lastObject];

        if (asset) {

            NSArray *delAssets = [[NSArray alloc] initWithObjects:asset, nil];

            [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{

                [PHAssetChangeRequest deleteAssets:delAssets];

            } completionHandler:^(BOOL success, NSError * _Nullable error) {

                

            }];

        }

    });

}

- (void)saveImageToPhotoAlbum:(UIImage*)savedImage{
    UIImageWriteToSavedPhotosAlbum(savedImage, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
}
//指定回调方法
- (void)image: (UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
    if (image == nil) {
        return;
    }
    NSString *msg = @"保存图片成功";
    if(error != NULL){
        msg = @"保存图片失败" ;
    }
    NSLog(@"🌹🌹🌹🌹%@",msg);
}


- (void)userDidTakeScreenshotNotification:(NSNotification *)notification {
    // 下面这张图与硬件截的图并不是同一张，这里再次使用代码截屏是为了获取用户截屏图片。
    UIImage *image = [self imageWithScreenshot];
    NSLog(@"HH");
    /*
     如果APP对保密要求比较高，这里可以将图片编码后上传到服务器，这样有需要时也可以提供一个追查方法。
     如果是自己的APP，再霸道一点的，这里监控到用户的截屏行为，应用直接强制退出登录并封号处理也是可以的。
     */
}

- (UIImage *)imageWithScreenshot {
    CGSize imageSize = CGSizeZero;
    UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
    if (UIInterfaceOrientationIsPortrait(orientation)) {
        imageSize = [UIScreen mainScreen].bounds.size;
    } else {
        imageSize = CGSizeMake([UIScreen mainScreen].bounds.size.height, [UIScreen mainScreen].bounds.size.width);
    }
    UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0);
    CGContextRef context = UIGraphicsGetCurrentContext();
    for (UIWindow *window in [[UIApplication sharedApplication] windows]) {
        CGContextSaveGState(context);
        CGContextTranslateCTM(context, window.center.x, window.center.y);
        CGContextConcatCTM(context, window.transform);
        CGContextTranslateCTM(context, -window.bounds.size.width * window.layer.anchorPoint.x, -window.bounds.size.height * window.layer.anchorPoint.y);
        if (orientation == UIInterfaceOrientationLandscapeLeft) {
            CGContextRotateCTM(context, M_PI_2);
            CGContextTranslateCTM(context, 0, -imageSize.width);
        } else if (orientation == UIInterfaceOrientationLandscapeRight) {
            CGContextRotateCTM(context, -M_PI_2);
            CGContextTranslateCTM(context, -imageSize.height, 0);
        } else if (orientation == UIInterfaceOrientationPortraitUpsideDown) {
            CGContextRotateCTM(context, M_PI);
            CGContextTranslateCTM(context, -imageSize.width, -imageSize.height);
        }
        if ([window respondsToSelector:@selector(drawViewHierarchyInRect:afterScreenUpdates:)]) {
            [window drawViewHierarchyInRect:window.bounds afterScreenUpdates:YES];
        } else {
            [window.layer renderInContext:context];
        }
        CGContextRestoreGState(context);
    }
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    NSData *imageData = UIImagePNGRepresentation(image);
    UIImage *screenImage = [UIImage imageWithData:imageData];
    return screenImage;
}

#pragma mark - UISceneSession lifecycle
- (UISceneConfiguration *)application:(UIApplication *)application configurationForConnectingSceneSession:(UISceneSession *)connectingSceneSession options:(UISceneConnectionOptions *)options {
    // Called when a new scene session is being created.
    // Use this method to select a configuration to create the new scene with.
    return [[UISceneConfiguration alloc] initWithName:@"Default Configuration" sessionRole:connectingSceneSession.role];
}


- (void)application:(UIApplication *)application didDiscardSceneSessions:(NSSet<UISceneSession *> *)sceneSessions {
    // Called when the user discards a scene session.
    // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
    // Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
/*
注意：此处的方法已经废弃
 */
//shortitem监听用户点击哪一个选项进入到程序
- (void)application:(UIApplication *)application performActionForShortcutItem:(UIApplicationShortcutItem *)shortcutItem completionHandler:(void (^)(BOOL))completionHandler{
    //不管APP在后台还是进程被杀死，只要通过主屏快捷操作进来的，都会调用这个方法
    
//    NSString *type = shortcutItem.type;
//    
//    if([type isEqualToString:@"messgae"]){
//        NSLog(@"新消息");
//    }else if([type isEqualToString:@"search"]){
//        NSLog(@"搜索");
//    }else if([type isEqualToString:@"collect"]){
//        NSLog(@"收藏");
//    }else if([type isEqualToString:@"share"]){
//        NSLog(@"分享");
//    }
    

    
    
}

//- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window{
    //
//    return UIInterfaceOrientationPortrait;
//}

@end
